package com.yimi.policyservice.repository;

import com.yimi.policyservice.entity.base.policy.PolicyAddr;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * @author jack
 */
public interface PolicyAddressRepository  extends JpaRepository<PolicyAddr,String> {
    @Query(value = "select  P from PolicyAddr P WHERE ( ?1 is null or P.cityName like %?1%)")
    Page<PolicyAddr> search(String key, PageRequest pageRequest);

    PolicyAddr findFirstByAddrName(String addrName);

    @Query(value = "select * from t_policy_addr a  where a.id in (select s.policy_addr_id from t_policy_social s)",nativeQuery = true)
    List<PolicyAddr> findSocialAddr();

    @Query(value = "select * from t_policy_addr a  where a.id in (select s.policy_addr_id from t_policy_accfund s)",nativeQuery = true)
    List<PolicyAddr> findAccfundAddr();

    @Query(value = "select * from t_policy_addr a  where a.id in  ( select  data_value from t_sys_user_data_permission where user_id = ?1 and data_type in(?2)) ",nativeQuery = true)
    List<PolicyAddr>findAllByPermission(String userId,List<Integer> permissionTypes);

    @Query(value = " " +
            "select count(*) from ( " +
            "                       select id " +
            "                       from t_policy_accfund_supp_rule " +
            "                       where policy_addr_id in (?1) " +
            "                       union " +
            "                       select id " +
            "                       from t_policy_social_supp_rule " +
            "                       where policy_addr_id in (?1) " +
            "                       union " +
            "                       select id " +
            "                       from t_policy_social_product " +
            "                       where addr_id in (?1) " +
            "                       union " +
            "                       select id " +
            "                       from t_policy_accfund_product " +
            "                       where addr_id in (?1) " +
            "                       union " +
            "                       select id " +
            "                       from t_policy_disabilities_product " +
            "                       where addr_id in (?1) " +

            "                     ) tmp",nativeQuery = true)
    int countByUseIds(List<String> ids);
}
